package servlet;

import service.UserService;
import model.User;
import util.SessionUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private UserService userService = new UserService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // Using redirect since login.html is in webapp root directory
        response.sendRedirect("login.html");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        try (PrintWriter out = response.getWriter()) {
            String username = request.getParameter("username");
            String password = request.getParameter("password");

            System.out.println("Received login request - Username: " + username);

            // Parameter validation
            if (username == null || username.trim().isEmpty() ||
                    password == null || password.trim().isEmpty()) {
                out.println("<script>alert('Username and password cannot be empty');history.back();</script>");
                return;
            }

            // Call UserService for authentication
            User user = userService.login(username, password);

            if (user != null) {
                // Set login status using SessionUtils
                SessionUtils.setCurrentUser(request, user);
                System.out.println("User login successful, Session ID: " + request.getSession().getId());

                out.println("<script>alert('Login successful!');location.href='index.jsp';</script>");
            } else {
                out.println("<script>alert('Login failed, incorrect username or password');history.back();</script>");
            }
        } catch (Exception e) {
            e.printStackTrace();
            // Use try-with-resources so we don't need to explicitly close PrintWriter
            try (PrintWriter out = response.getWriter()) {
                out.println("<script>alert('System error, please try again later');history.back();</script>");
            }
        }
        // Removed explicit PrintWriter close call - handled automatically by container
    }
}
